package com.bigfans.framework.utils;

import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 字符串帮助类
 */
public final class PinyinHelper {
	
	/**
	* 只转换汉字为拼音，其他字符不变
	* @param inputString
	* @return
	*/
	public static String toHanyupinyin(String inputString){
		//汉语拼音格式输出类
		HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
		//输出设置，大小写，音标方式等
		hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); //小写
		hanYuPinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); //无音调
		hanYuPinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE); //'¨¹' is "v"
		char[] input = inputString.trim().toCharArray();
		StringBuffer output = new StringBuffer();
		for(int i=0;i<input.length;i++){
			//是中文转换拼音(我的需求，是保留中文)
			if(Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")){ //中文字符
				try{
					String[] temp = net.sourceforge.pinyin4j.PinyinHelper.toHanyuPinyinStringArray(input[i],hanYuPinOutputFormat);
					output.append(temp[0]);
				}catch(BadHanyuPinyinOutputFormatCombination e){
				e.printStackTrace();
				}
			}else{ //其他字符
				output.append(Character.toString(input[i]));
			}
		}
		return output.toString();
	}
	
}
